package com.tian.authen.exception;


import com.tian.common.result.BaseResult;
import com.tian.common.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author zhump
 */
@ControllerAdvice
public class GlobalExceptionHandler {



    /**
     * 全局注解异常
     *
     * @param exception 异常
     * @return 结果集
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public BaseResult handlerException(BindException exception) {
        return Result.illegalArgument(getMsg(exception.getBindingResult().getAllErrors()));

    }
    /**
     * 返回注解异常的返回值
     *
     * @param objectErrors 异常处理结果集
     * @return 结果集
     */
    private String getMsg(List<ObjectError> objectErrors) {
        StringBuffer stringBuffer = new StringBuffer();

        int index = 0;
        for (ObjectError objectError : objectErrors) {
            stringBuffer.append(objectError.getDefaultMessage());
            index++;
            if (index != objectErrors.size()) {
                stringBuffer.append(";");
            }
        }
        return stringBuffer.toString();
    }

}
